import { refreshTokenApi } from '@/api/login'
import { useUserStoreWithOut } from '@/store/modules/user'
import { Log } from '@/utils/logError'
import { InternalAxiosRequestConfig } from 'axios'

let promise: Promise<any> | null = null

export function refreshToken() {
  const userStore = useUserStoreWithOut()
  promise = new Promise((resolve) => {
    const refreshToken = (userStore.getTokenPrefix ?? '') + (userStore.getRefreshToken ?? '')
    refreshTokenApi(refreshToken).then((res) => {
      const { token, isDoubleToken } = res.data
      userStore.setToken(token, isDoubleToken)
      resolve(token.accessToken)
    })
  })
  promise.catch((err) => {
    Log.error('refreshToken', err)
  })
  promise.finally(() => {
    promise = null
  })
  return promise
}

export function isRefreshRequest(config: InternalAxiosRequestConfig) {
  return !!config.headers.RefreshToken
}
